package com.tanger.permission.permission.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanger.common.result.ActionResult;
import com.tanger.common.utils.MapUtils;
import com.tanger.common.utils.RecursiveUtils;
import com.tanger.permission.entity.permission.EntityRolePermission;
import com.tanger.permission.entity.vo.RolePermissionVo;
import com.tanger.permission.mapper.permission.RolePermissionMapper;
import com.tanger.permission.permission.service.RolePermissionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;


/**
 * @Description 角色权限实现类
 * @Author Hchenbin
 * @Date 2022/6/29 15:55
 * @Version 1.0
 */
@Service
public class RolePermissionServiceImpl implements RolePermissionService{

    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    private static Logger logger = LoggerFactory.getLogger(RolePermissionServiceImpl.class);

    @Override
    public List<RolePermissionVo> RolepermissionInfo(Long roleId){
        List<LinkedHashMap<String, Object>> list = RecursiveUtils.queryRecursiveList(rolePermissionMapper.queryRolePermissionByRoleId(roleId),"permission");
        List<RolePermissionVo> resultList = new ArrayList<>();
        resultList = converBool(resultList, list);
        return Optional.ofNullable(resultList).orElse(new ArrayList<>());
    }

    @Override
    public ActionResult savaRolePermission(Long roleId,List<EntityRolePermission> list) {
        rolePermissionMapper.delete(new QueryWrapper<EntityRolePermission>().eq("role_id",roleId));
        list.forEach(x -> {
            x.setRoleId(roleId);
            rolePermissionMapper.insert(x);
        });
        return ActionResult.buildResultSuccess();
    }

    @Override
    public ActionResult deleteRolePermission(Long[] ids) {
        rolePermissionMapper.deleteBatchIds(Arrays.asList(ids));
        return ActionResult.buildResultSuccess();
    }

    @Override
    public ActionResult deleteRolePermissionByRoleId(Long roleId) {
        rolePermissionMapper.delete(new QueryWrapper<EntityRolePermission>().eq("role_id",roleId));
        return ActionResult.buildResultSuccess();
    }

    /**
     * 重构数据结构
     */
    private List<RolePermissionVo> converBool( List<RolePermissionVo> resultList, List<LinkedHashMap<String, Object>> list){
        if (CollectionUtils.isEmpty(list)) return null;
        list.stream().forEach(x -> {
            RolePermissionVo parentVo = MapUtils.toObj(x,RolePermissionVo.class);
            resultList.add(parentVo);
        });
        return resultList;
    }
}
